package com.agrec.server;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.agrec.client.UserToken;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.agrec.client.actors.CitiesNames;
import com.agrec.client.actors.CompaniesNames;
import com.agrec.client.actors.User;
import com.agrec.client.services.UserService;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class UserServiceImpl extends RemoteServiceServlet implements
		UserService {

	public UserServiceImpl() {
		DatabaseManager.instance();
	}
	
	public String greetServer(String input) {
		String serverInfo = getServletContext().getServerInfo();
		String userAgent = getThreadLocalRequest().getHeader("User-Agent");
		return "Hello, " + input + "!<br><br>I am running " + serverInfo
				+ ".<br><br>It looks like you are using:<br>" + userAgent;
	}
	
	public UserToken login(String userName, String password)  {
		
		//if (userName.equals("userName") && password.equals("password"))
		//	return new UserToken();
		
		//return null;
		User user = null;
		try {
			user = DatabaseManager.getUser(userName);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if (user == null)
			return null;
		UserToken token = null;
		
		
		
		if (user.password().equals(password)) {
			token = new UserToken();
			token.token(""+UUID.randomUUID());
			token.userName(user.userName());
			//save it in your database with a pointer to the user record. 
			DatabaseManager.addUserToken(user.id(), token.token());
			
			//You can add in a date/time of you want to record it and/or if you want to time people out, 
			//user.loginTime = new Timestamp(System.currentTimeMillis());
			
			//token+="::" + (user.loginTime.compareTo(new Date(System.currentTimeMillis())));
			//save IP address if you want to restrict admin to certain IP addresses
			String userIP = getThreadLocalRequest().getRemoteAddr();
			token.userIP(userIP);
			
			//save the browser ID string. 
			//The server can always check the browser ID string (user agent). 
			//This ensures that any spoofer has to use the same browser and OS or it won't work.
			String userAgent = getThreadLocalRequest().getHeader("User-Agent");
			token.userAgent(userAgent);
			
			System.out.println("Login Successful" );
			//added the token to Database
			
		}
		return token;
	}
}
